1 /****************************** Module Header ******************************\
2 Module Name: FileController.cs
3 Project: CSASPNETMVCFileDownload
4 Copyright (c) Microsoft Corporation.
6 This module contains the FileController class.
8 FileController is the controller dedicated for file downloading functionality.
9 For request to list file, FileController will call List Action to return the
10 file list and display it via File/List view
12 File request to download a certain file, FileController will call the
13 Download action to return the stream of the requested file.
15 This source is subject to the Microsoft Public License.
16 See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
17 All other rights reserved.
19 THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
20 EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
21 WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
22 \***************************************************************************/
25 using System
.Collections
.Generic
;
29 using System
.Web
.Mvc
.Ajax
;
33 namespace CSASPNETMVCFileDownload
.Controllers
35 public class FileController
: Controller
37 // Action for list all the files in "~/App_Data/download" directory
38 public ActionResult
List()
40 // Retrieve the file list.
41 DirectoryInfo dir
= new DirectoryInfo(Server
.MapPath("~/App_Data/download/"));
43 // Filter it via LINQ to Object.
44 var files
= from f
in dir
.GetFiles("*.*", SearchOption
.TopDirectoryOnly
)
45 where f
.Extension
!= "exe"
48 // Call the corresponding View.
49 return View(files
.ToList());
52 // Action for returning the binary stream of a specified file.
53 public ActionResult
Download(string fn
)
55 // Check whether the requested file is valid.
56 string pfn
= Server
.MapPath("~/App_Data/download/" + fn
);
57 if (!System
.IO
.File
.Exists(pfn
))
59 throw new ArgumentException("Invalid file name or file not exists!");
62 // Use BinaryContentResult to encapsulate the file content and return it.
63 return new BinaryContentResult()
66 ContentType
= "application/octet-stream",
67 Content
= System
.IO
.File
.ReadAllBytes(pfn
)